// View.cs
//
//  Copyright (C) 2008 George Talusan
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
//

using Gecko;

using Mono.Picnik.Core;
using Mono.Picnik.UI;

using System.Text;
using System.Web;
using System;

namespace Mono.Picnik.UI.Gtk
{
	public class View : WebControl, ViewInterface
	{
		public View() : base ()
		{
			OpenUri += OpenUriHandler;
		}
		
		private Request _request;
		public Request Request
		{
			get { return _request; }
			set { _request = value; }
		}

		public void Render ()
		{
			LoadUrl ("about:blank");
			
			byte[] picnikBytes = Service.Publish (Request);
			string picnikURI = Encoding.UTF8.GetString (picnikBytes);
			LoadUrl (picnikURI);
		}

		public void OpenUriHandler (object o, OpenUriArgs args)
		{
			string url = HttpUtility.UrlDecode (args.AURI);
			Console.WriteLine (url);
			/*if (url.IndexOf ("adsrv") >= 0)
			{
				args.RetVal = true;
			}
			else */if (url.IndexOf (Request.Export) >= 0)
			{
				Uri uri = new Uri (url);
				string query = uri.Query;
				string[] parts = query.Split ('&', '?');
				foreach (string part in parts)
				{
					string[] arg = part.Split ('=');
					if (arg[0].Equals (Request.ExportField))
					{
						args.RetVal = true;
						byte[] picnikBytes = Service.Download (arg[1]);
						Request.ResponseAsBytes = picnikBytes;
					}
				}
			}
		}
	}
}
